package com.sunseagear.wind.modules.sys.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunseagear.common.base.http.R;
import com.sunseagear.common.base.http.RPage;
import com.sunseagear.common.base.mvc.controller.BaseBeanController;
import com.sunseagear.common.datarule.handler.DataRuleHandler;
import com.sunseagear.common.utils.ObjectUtils;
import com.sunseagear.wind.common.aspectj.annotation.Log;
import com.sunseagear.wind.common.aspectj.enums.LogType;
import com.sunseagear.wind.modules.sys.dto.RoleDataUpdateDto;
import com.sunseagear.wind.modules.sys.entity.DataRule;
import com.sunseagear.wind.modules.sys.entity.RoleDataRule;
import com.sunseagear.wind.modules.sys.entity.query.RoleDataRuleQuery;
import com.sunseagear.wind.modules.sys.service.IDataRuleService;
import com.sunseagear.wind.modules.sys.service.IRoleDataRuleService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 *
 * @version V1.0
 * @package sys
 * @title: 角色数据权限关联表控制器
 * @description: 角色数据权限关联表控制器
 * @author: 未知
 * @date: 2019-12-03 13:03:38
 * @copyright: www.sunseagear.com Inc. All rights reserved.
 */

@RestController
@RequestMapping("sys/roledatarule")
@Log(title = "角色数据权限关联表")
@RequiredArgsConstructor
public class RoleDataRuleController extends BaseBeanController {

    private final IRoleDataRuleService roleDataRuleService;
    private final IDataRuleService dataRuleService;
    private final DataRuleHandler dataRuleHandler;

    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     */
    @GetMapping(value = "list")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("sys:datarule:list")
    public RPage<DataRule> list(RoleDataRuleQuery query) {
        //加入条件
        QueryWrapper<RoleDataRule> roleDataRuleEntityWrapper = new QueryWrapper<>();
        roleDataRuleEntityWrapper.lambda().eq(RoleDataRule::getRoleId, query.getRoleId());
        // 预处理
        List<RoleDataRule> list = roleDataRuleService.list(roleDataRuleEntityWrapper);

        QueryWrapper<DataRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(DataRule::getCreateDate)
                .eq(ObjectUtils.isNotEmpty(query.getResourceCode()),DataRule::getResourceCode, query.getResourceCode())
                .eq(ObjectUtils.isNotEmpty(query.getScopeName()),DataRule::getScopeName, query.getScopeName());
        // 预处理
        Page<DataRule> pageBean = dataRuleService.page(getPage(), queryWrapper);
        pageBean.getRecords().forEach(item -> list.forEach(roleDataRule -> {
            if (item.getId().equals(roleDataRule.getScopeId())) {
                item.setSelect(true);
            }
        }));
        return RPage.success(pageBean);
    }
    /**
     * 新增
     * @param entity 实体参数
     * @return 操作结果
     */
    @PostMapping("add")
    @Log(logType = LogType.INSERT)
    @SaCheckPermission("sys:datarule:add")
    public R<Void> add(@Validated @RequestBody RoleDataRule entity) {
        roleDataRuleService.save(entity);
        return R.success("添加成功");
    }

    /**
     * 更新
     * @param entity 实体参数
     * @return 操作结果
     */
    @PutMapping("update")
    @Log(logType = LogType.UPDATE)
    @SaCheckPermission("sys:datarule:update")
    public R<Void> update(@Validated @RequestBody RoleDataRule entity) {
        roleDataRuleService.saveOrUpdate(entity);
        return R.success("更新成功");
    }

    /**
     * 批量更新
     * @param dto 参数
     * @return 操作结果
     */
    @PostMapping("updateRules")
    @Log(logType = LogType.UPDATE)
    @SaCheckPermission("sys:datarule:update")
    public R<Void> update(@Validated @RequestBody RoleDataUpdateDto dto) {
        QueryWrapper<RoleDataRule> roleDataRuleEntityWrapper = new QueryWrapper<>();
        roleDataRuleEntityWrapper.lambda().eq(RoleDataRule::getRoleId, dto.getRoleId());
        roleDataRuleService.remove(roleDataRuleEntityWrapper);
        if (dto.getIds() == null) {
            dataRuleHandler.refreshRole();
            return R.success("更新成功");
        }
        List<RoleDataRule> roleDataRuleList = new ArrayList<>();
        dto.getIds().forEach(item -> {
            RoleDataRule roleDataRule = new RoleDataRule();
            roleDataRule.setRoleId(dto.getRoleId());
            roleDataRule.setScopeId(item);
            roleDataRuleList.add(roleDataRule);
        });
        roleDataRuleService.saveBatch(roleDataRuleList);
        dataRuleHandler.refreshRole();
        return R.success("更新成功");
    }

    /**
     * 获取详细信息
     * @param id 主键id
     * @return 详情
     */
    @GetMapping("detail/{id}")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("sys:datarule:detail")
    public R<RoleDataRule> detail(@PathVariable("id") Long id) {
        RoleDataRule roleDataRule = roleDataRuleService.getById(id);
        return R.success(roleDataRule);
    }

    /**
     * 删除
     * @param idList 主键集合
     * @return 操作结果
     */
    @DeleteMapping("delete")
    @Log(logType = LogType.DELETE)
    @SaCheckPermission("sys:datarule:delete")
    public R<Void> delete(@RequestBody List<Long> idList) {
        roleDataRuleService.removeBatchByIds(idList);
        return R.success("删除成功");
    }
}
